package initialize

import (
	"example.com/m/v2/global"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func Gorm() *gorm.DB {
	conf := global.GVA_CONFIG.Mysql

	if conf.DbName == "" {
		return nil
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?timeout=%s&parseTime=true", conf.Username, conf.Password, conf.Host, conf.Port, conf.DbName, conf.Timeout)

	mysqlConfig := mysql.Config{
		DSN:                       dsn,
		SkipInitializeWithVersion: false, // 根据版本自动配置
	}

	if db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{}); err != nil {
		return nil
	} else {
		db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(10)
		sqlDB.SetMaxOpenConns(100)
		return db
	}
}
